package com.wutong.resonance.model.audio.header;

import lombok.AllArgsConstructor;
import lombok.Getter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteOrder;

/**
 * 文件头部信息
 * @author wutong
 */
@Getter
@AllArgsConstructor
public abstract class FileHeader {
    // 原字段保持不变
    private int chunkId;
    private int chunkSize;
    private int format;
    private int subchunk1Id;
    private int subchunk1Size;
    private short audioFormat;
    private short numChannels;
    private int sampleRate;
    private int byteRate;
    private short blockAlign;
    private short bitsPerSample;
    private int subchunk2Id;
    private int subchunk2Size;

    // 新增字节序字段
    private final ByteOrder byteOrder;

    // 移除非抽象方法，统一处理字节序
    protected void writeShort(ByteArrayOutputStream bos, int s) throws IOException {
        if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
            bos.write(s & 0xFF);
            bos.write((s >> 8) & 0xFF);
        } else {
            bos.write((s >> 8) & 0xFF);
            bos.write(s & 0xFF);
        }
    }

    protected void writeInt(ByteArrayOutputStream bos, int n) throws IOException {
        if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
            bos.write(n & 0xFF);
            bos.write((n >> 8) & 0xFF);
            bos.write((n >> 16) & 0xFF);
            bos.write((n >> 24) & 0xFF);
        } else {
            bos.write((n >> 24) & 0xFF);
            bos.write((n >> 16) & 0xFF);
            bos.write((n >> 8) & 0xFF);
            bos.write(n & 0xFF);
        }
    }

    protected void writeChar(ByteArrayOutputStream bos, char[] id) {
        for (char c : id) {
            bos.write((byte) c);
        }
    }

    public abstract byte[] getHeader();
}
